import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import './address.css'

// 地址类型定义
interface Address {
  id: string
  recipient: string
  phone: string
  region: string
  detailAddress: string
  isDefault: boolean
}

function Index() {
  const navigate = useNavigate()
  const location = useLocation()
  const [addresses, setAddresses] = useState<Address[]>([])

  // 从 localStorage 加载地址数据
  useEffect(() => {
    const savedAddresses = localStorage.getItem('addresses')
    if (savedAddresses) {
      setAddresses(JSON.parse(savedAddresses))
    }
  }, [])

  // 保存地址数据到 localStorage
  const saveAddressesToStorage = (newAddresses: Address[]) => {
    localStorage.setItem('addresses', JSON.stringify(newAddresses))
    setAddresses(newAddresses)
  }

  // 添加新地址
  const addAddress = (newAddress: Omit<Address, 'id'>) => {
    const addressWithId = {
      ...newAddress,
      id: Date.now().toString()
    }
    
    let updatedAddresses = [...addresses]
    
    // 如果新地址设为默认，取消其他地址的默认状态
    if (newAddress.isDefault) {
      updatedAddresses = updatedAddresses.map(addr => ({
        ...addr,
        isDefault: false
      }))
    }
    
    updatedAddresses.push(addressWithId)
    saveAddressesToStorage(updatedAddresses)
  }

  // 删除地址
  const deleteAddress = (id: string) => {
    const updatedAddresses = addresses.filter(addr => addr.id !== id)
    saveAddressesToStorage(updatedAddresses)
  }

  // 设置默认地址
  const setDefaultAddress = (id: string) => {
    const updatedAddresses = addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === id
    }))
    saveAddressesToStorage(updatedAddresses)
  }

  // 编辑地址
  const editAddress = (id: string) => {
    navigate(`/address/edit/${id}`)
  }

  // 处理从添加页面返回的数据
  useEffect(() => {
    if (location.state?.newAddress) {
      addAddress(location.state.newAddress)
      // 清除状态，避免重复添加
      navigate(location.pathname, { replace: true })
    }
  }, [location.state, navigate, location.pathname])

  return (
    <div className="address-page">
      {/* 顶部导航栏 */}
      <div className="address-header">
        <button className="back-btn" onClick={() => navigate('/ment')}>
          ←
        </button>
        <div className="header-title">收货地址</div>
      </div>

      {/* 内容区域 */}
      <div className="address-content">
        {addresses.length === 0 ? (
          <div className="empty-state">
            <div className="empty-text">暂无收货地址哦~</div>
          </div>
        ) : (
          <div className="address-list">
            {addresses.map((address) => (
              <div key={address.id} className="address-item">
                <div className="address-info">
                  <div className="address-header-row">
                    <span className="recipient-name">{address.recipient}</span>
                    <span className="phone-number">{address.phone}</span>
                    {address.isDefault && <span className="default-tag">默认</span>}
                  </div>
                  <div className="address-detail">
                    {address.region} {address.detailAddress}
                  </div>
                </div>
                <div className="address-actions">
                  <button 
                    className="action-btn edit-btn"
                    onClick={() => editAddress(address.id)}
                  >
                    编辑
                  </button>
                  <button 
                    className="action-btn delete-btn"
                    onClick={() => deleteAddress(address.id)}
                  >
                    删除
                  </button>
                  {!address.isDefault && (
                    <button 
                      className="action-btn default-btn"
                      onClick={() => setDefaultAddress(address.id)}
                    >
                      设为默认
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 底部添加按钮 */}
      <div className="bottom-action">
        <button className="add-address-btn" onClick={() => navigate('/address/add')}>
          <span className="add-icon">+</span>
          添加收货地址
        </button>
      </div>
    </div>
  )
}

export default Index
